package com.example.jswebtext

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.widget.AppCompatEditText
import com.just.agentweb.*

open class MainActivity : AppCompatActivity() {
    private var mAgentWeb: AgentWeb? = null
    private var preWeb: AgentWeb.PreAgentWeb? = null
    private var container: LinearLayout? = null
    private var url = "file:///android_asset/js_interaction/hello.html"
    private lateinit  var startLog: AppCompatEditText
    private lateinit var type: AppCompatEditText
    private lateinit var code: AppCompatEditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        container = findViewById(R.id.container)
        startLog = findViewById(R.id.startAddress)
        type = findViewById(R.id.endAddress)
        code = findViewById(R.id.num_et)
        findViewById<View>(R.id.loaction).setOnClickListener(mOnClickListener)
        findViewById<View>(R.id.nav).setOnClickListener(mOnClickListener)
//        findViewById<View>(R.id.jsJavaCommunicationButton).setOnClickListener(mOnClickListener)
        init()
    }

    private fun init() {
        preWeb = AgentWeb.with(this)
            .setAgentWebParent(container!!, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
//            .setWebViewClient(WebViewClient())
//            .setWebChromeClient(WebChromeClient())
//            .setPermissionInterceptor(mPermissionInterceptor) //权限拦截 2.0.0 加入。
//            .setAgentWebWebSettings(getSettings())//设置 IAgentWebSettings。
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
//            .setMainFrameErrorView(R.layout.layout_error, -1)
//            .useMiddlewareWebChrome(getMiddlewareWebChrome()) //设置WebChromeClient中间件，支持多个WebChromeClient，AgentWeb 3.0.0 加入。
//            .useMiddlewareWebClient(getMiddlewareWebClient()) //设置WebViewClient中间件，支持多个WebViewClient， AgentWeb 3.0.0 加入。
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
//            .setWebLayout(WebLayout(this))
            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
            .createAgentWeb()
            .ready()
//            .go(mViewModel.url)
        //加载网页
//        LogUtils.d("网页$mType-->" + mViewModel.url)
        mAgentWeb = preWeb?.go(url)

        if (mAgentWeb != null) {
            //注入对象
            mAgentWeb!!.jsInterfaceHolder.addJavaObject(
                "android",
                AndroidInterface(mAgentWeb, this)
            )
        }

        onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    mAgentWeb?.let { web ->
                        if (web.webCreator.webView.canGoBack()) {
                            web.webCreator.webView.goBack()
                        } else {
                            finish()
                        }
                    }
                }
            })

    }

    private val mOnClickListener =
        View.OnClickListener { v ->
            when (v.id) {
//                定位
                R.id.loaction -> mAgentWeb!!.jsAccessEntrace.quickCallJs(
                    "locationFromNatives",
                    "114.304569", "30.593354",
                )
//                导航
                R.id.nav -> {
                    if (startLog.text!!.isEmpty()){
                        Toast.makeText(this,"请输入起点",Toast.LENGTH_SHORT).show()
                        return@OnClickListener
                    }

                    if (type.text!!.isEmpty()){
                        Toast.makeText(this,"停车场出口编号",Toast.LENGTH_SHORT).show()
                        return@OnClickListener
                    }
                    if (code.text!!.isEmpty()){
                        Toast.makeText(this,"编号",Toast.LENGTH_SHORT).show()
                        return@OnClickListener
                    }
                    var lat = ""
                    var log = ""
                    val loglat = startLog.text.toString().split(",")
                    if (loglat.isNotEmpty()){
                         log = loglat[0]
                        if (loglat.size>1){
                            lat = loglat[1]
                        }
                    }
                    if (lat.isEmpty() || log.isEmpty()){
                        Toast.makeText(this,"起点坐标不正确",Toast.LENGTH_SHORT).show()
                        return@OnClickListener
                    }


                    mAgentWeb!!.jsAccessEntrace.quickCallJs(
                        "navigationFromNatives",log,lat, type.text.toString(),code.text.toString()
                    )
//                        "114.304569,30.593354", "1", "1"
                }
//                R.id.jsJavaCommunicationButton-> mAgentWeb!!.jsAccessEntrace.quickCallJs(
//                    "callByAndroidInteraction",
//                    "你好Js"
//                )
            }
        }


    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAgentWeb?.webLifeCycle?.onDestroy()
    }
}